package com.cps.data.jpa.dao;

import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;

/**
 * Created by Jensen on 2016/9/28.
 */
@Transactional
public class BaseDaoImpl<T,ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseDao<T,ID>{

    private final EntityManager em;

    public BaseDaoImpl(Class<T> domainClass, javax.persistence.EntityManager em) {
        super(domainClass, em);
        this.em=em;
    }


    public List selectByHql(String hql) {
        return this.em.createQuery(hql).getResultList();
    }

    public List selectByHql(String hql, Object[] params) {
        Query query=this.em.createQuery(hql);
        setQueryParams(query,params);
        return query.getResultList();
    }

    public List<T> findByHql(String hql) {
        Query query=this.em.createQuery(hql);
        return query.getResultList();
    }

    public List<T> findByHql(String hql, Object[] params) {
        Query query=this.em.createQuery(hql);
        setQueryParams(query, params);
        return query.getResultList();
    }

    public int execByHql(String hql) {
        Query query=this.em.createQuery(hql);
        return query.executeUpdate();
    }

    public int execByHql(String hql, Object[] params) {
        Query query=this.em.createQuery(hql);
        setQueryParams(query,params);
        return query.executeUpdate();
    }

    public List selectBySql(String sql) {
        return this.em.createNativeQuery(sql).getResultList();
    }

    public List selectBySql(String sql, Object[] params) {
        Query query=this.em.createNativeQuery(sql);
        setQueryParams(query,params);
        return query.getResultList();
    }

    public List<T> QueryBySql(String sql) {
        Query query=this.em.createNativeQuery(sql);
        return query.getResultList();
    }

    public List<T> QueryBySql(String sql,Object[] params) {
        Query query=this.em.createNativeQuery(sql);
        setQueryParams(query, params);
        return query.getResultList();
    }

    public int execBySql(String sql) {
        Query query=this.em.createNativeQuery(sql);
        return query.executeUpdate();
    }

    public int execBySql(String sql, Object[] params) {
        Query query=this.em.createNativeQuery(sql);
        setQueryParams(query,params);
        return query.executeUpdate();
    }

    private void setQueryParams(Query query, Object[] params){
        if(params!=null && params.length>0){
            for (int i=0;i<params.length;i++){
                query.setParameter(i,params[i]);
            }
        }
    }




}
